<template>
    <div class="app-main-plus beautify">
      <div class="search-container">
        <el-row :gutter="10">
          <el-col :xs="18" :sm="18" :md="18" :lg="18" :xl="18">
            <el-button class="back-btn" type="default" size="small" plain icon="el-icon-arrow-left" @click="goBack">返回</el-button>
          </el-col>
          <el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6">
            <div class="pull-right">
              <div class="pull-right" v-if="canEditAdd()">
                <el-button v-show="!isDisabled" size="small" @click="submit" type="primary" >提交</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="content-container">
        <form-title title="匹配信息" ref="baseInfo">
          <zb-form
            v-bind="formOptions"
            :model="form"
            :editable="canEditAdd()"
            v-loading="loading"
            ref="form1"
            @handleChange="handleChange">
            <template slot="addLeCode">
              <div style="display: flex;flex: 1;text-align: left"><el-button type="primary" :disabled="!canEditAdd()" @click="addSupplier()" size="mini">新增承建商</el-button></div>
            </template>
          </zb-form>
        </form-title>
        <form-title title="关联预算编制流程">
          <el-table
            v-loading="loading" border ref="tableForm2" :data="form.bpmInfos">
            <el-table-column type="index" label="序号" width="120"  align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.flag" :true-label="1" size="small" :disabled="!canEditAdd()" @change="changeFlag"/>
              </template>
            </el-table-column>
            <el-table-column prop="bpmTitle" label="名称" align="center">
            </el-table-column>
            <el-table-column prop="createBy" label="流程发起人" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTime" label="流程发起时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="completeTime" label="流程结束时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="操作" label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="small" @click="getBpm(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </form-title>
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="承建商信息" name="first">
            <form-title title="基本信息">
              <zb-form
                v-bind="formOptions1"
                :model="form.supplier"
                v-loading="loading"
                :editable="false"
                ref="form2">
              </zb-form>
            </form-title>
            <form-title title="账号信息">
              <zb-form
                v-bind="formOptions2"
                :model="form.supplier"
                v-loading="loading"
                :editable="false"
                ref="form3">
              </zb-form>
            </form-title>
          </el-tab-pane>
        </el-tabs>

        <el-dialog width="70%" title="新增承建商信息" :visible.sync="visible" append-to-body :destroy-on-close="true">
          <div class="search-container">
            <el-row :gutter="10" span="24">
                <div class="pull-right">
                  <el-button v-show="!isDisabled" size="small" @click="submitAddSupplier" type="primary" >提交</el-button>
                </div>
            </el-row>
          </div>
          <form-title title="基本信息">
            <zb-form
              v-bind="formOptions1Clone"
              :model="formClone.supplier"
              v-loading="loading"
              :editable="true"
              ref="form2Clone">
            </zb-form>
          </form-title>
          <form-title title="账号信息">
            <zb-form
              v-bind="formOptions2Clone"
              :model="formClone.supplier"
              v-loading="loading"
              :editable="true"
              ref="form3Clone">
            </zb-form>
          </form-title>
        </el-dialog>
      </div>
    </div>
</template>

<script>
  import FormTitle from "@/views/components/FormTitle";
  import BaseBpm from "@/views/base/BaseBpm";
  import BasePagination from "@/views/base/BasePagination";
  import BaseIndex from "@/views/base/BaseIndex";
  import {getToken} from "@/utils/auth";
  import {newWindowBpm} from "@/utils/openBpm";
  import {addContractorMatchingDetail, updateContractorMatchingDetail,getContractorMatchingDetail,getProjectBudget,getTotalBudget,submitAddSupplier} from "@/api/resourceMatching/contractorMatching";
  import Index from "./index";
    export default {
      name: "ContractorMatchingDetail",
      components: {BaseBpm, BasePagination ,FormTitle},
      extends:BaseIndex,
      data() {
          return {
            visible:false,
            sonListHeight: 0,
            sonList:[],
            sonListItem:{
            },
            activeName: 'first',
            form:{supplier:{}},
            formClone:{supplier:{}},
            formOptions:{
              labelWidth: "160px",
              rules: {
                projectName: [
                  { required: true, message: "项目名称 不能为空", trigger: "blur" }
                ],
                'supplier.name': [
                  { required: true, message: "承建商 不能为空", trigger: "blur" }
                ],
                scope: [
                  { required: true, message: "承建范围 不能为空", trigger: "blur" }
                ],
                projectBuildType: [
                  { required: true, message: "立项类型 不能为空", trigger: "blur" }
                ],
              },
              options: [
                {
                  label: "项目名称",
                  prop: "projectName",
                  type: "selectData",
                  searchKey: "projectName",
                  span: 8,
                  url: `${process.env.VUE_APP_BASE_API}/pigfarm-project/like`,
                  props: {
                    label: "projectName",
                    value: "projectId"
                  },
                  height:62,
                  getDictSuccessStatus:0,
                  getDictResultMap:{
                    status:'data.code',
                    data:'data.data',
                    list:'data.data.records',
                    total:'data.data.total',
                  },
                  // 不在创建的时候就请求数据，false
                  createdRequest: false,
                  searchAbel: false,
                  selectAble: true,
                  searchIconVisible:true,
                  dialogType:2,
                  labelFields:['pigfarmName','pigfarmNumber','projectName','projectNumber'],
                  labelFieldsName:['猪场名称','猪场编号','项目名称','项目编号'],
                  searchLabel:['projectName'],
                  searchLabelName:['项目名称'],
                  headers:{
                    Authorization:'Bearer '+ getToken()
                  },
                  listeners: {
                    dataChange: val => {
                      if (val){
                        // 都是自动带出的
                        this.$set(this.form,'projectNumber',val.projectNumber)
                        this.$set(this.form,'projectId',val.projectId)
                        this.$set(this.form,'projectName',val.projectName)
                        this.$set(this.form,'pigfarmName',val.pigfarmName)
                        this.$set(this.form,'pigfarmId',val.pigfarmId)
                        this.$set(this.form,'pigfarmNumber',val.pigfarmNumber)
                        this.$set(this.form,'projectBuildType',val.projectBuildType)
                        this.$set(this.form,'instId',val.instId)
                        this.loading = true
                        getProjectBudget({projectId:val.projectId,type:'budget'})
                          .then((res)=>{
                            if (res.code===0){
                              this.form.bpmInfos = res.data
                            }
                            this.loading = false
                          })
                          .catch(()=>{
                            this.loading = false
                        })
                      }
                    }
                  }
                },
                {
                  label: "猪场名称",
                  prop: "pigfarmName",
                  type: 'text',
                  span: 8,
                  height:62,
                  disabled: true,
                },
                {
                  label: "预算金额",
                  prop: "totalBudget",
                  type: 'number',
                  disabled: true,
                  span: 8,
                  height:62,
                },
                {
                  label: "申请人",
                  prop: "createName",
                  type: 'text',
                  span: 8,
                  disabled: true,
                  height:62,
                },
                {
                  label: "申请时间",
                  prop: "createTime",
                  type: 'date',
                  format:'yyyy-MM-dd',
                  valueFormat:'yyyy-MM-dd',
                  span: 8,
                  disabled: true,
                  height:62,
                },
                {
                  label: "承建范围",
                  prop: "scope",
                  type: 'text',
                  maxLength: 100,
                  span: 8,
                  height:62,
                },
                {
                  label: "承建商",
                  prop: "supplier.name",
                  type: "selectData",
                  searchKey: "name",
                  span: 6.2,
                  url: `${process.env.VUE_APP_BASE_API}/base-supplier/like`,
                  props: {
                    label: "name",
                    value: "leCode"
                  },
                  dialogType:2,
                  labelFields:['name','number','bankName','address'],
                  labelFieldsName:['名称','编码','银行名称','地址'],
                  searchLabel:['name'],
                  searchLabelName:['承建商名称'],
                  getDictSuccessStatus:0,
                  getDictResultMap: {
                    status:'data.code',
                    data:'data.data',
                    total:'data.data.total',
                    list:'data.data.records',
                  },
                  searchAbel: false,
                  selectAble: false,
                  searchIconVisible:true,
                  createdRequest: false,
                  headers:{
                    Authorization:'Bearer ' + getToken()
                  },
                  listeners: {
                    dataChange: val => {
                      if (val){
                        // 都是自动带出的
                        this.$set(this.form,'supplier',val)
                      }
                    }
                  },
                  height:62,
                },
                {
                  hiddenLabel:true,
                  span: 1.8,
                  prop: 'addLeCode',
                  type: 'slot',
                  height:62,
                  style: 'border-left:0px'
                },
                {
                  label: "附件",
                  prop: "matchFiles",
                  type: 'file',
                  span: 8,
                  limit:4,
                  url:`${process.env.VUE_APP_BASE_API}/file/upload`,
                  downUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
                  previewUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
                  headers:{
                    Authorization:'Bearer '+getToken()
                  },
                  height: 62,
                  resultDataMap:{
                    fileName:'',
                    filePath:'',
                  }
                },
                {
                  label: "立项类型",
                  prop: "projectBuildType",
                  type: 'select',
                  span: 8,
                  height:62,
                  options:[
                    {value:'1',label:'猪场技改'},
                    {value:'2',label:'环保技改'},
                    {value:'3',label:'未批先建'},
                    {value:'4',label:'数据补录'},
                  ]
                },
                {
                  label: "备注",
                  prop: "remark",
                  type: 'textarea',
                  height: 100,
                  span: 24,
                },
              ]
            },
            formOptions1:{
              labelWidth: "160px",
              rules: {
                number: [
                  { required: true, message: "公司编号 不能为空", trigger: "blur" }
                ],
                name: [
                  { required: true, message: "单位名称 不能为空", trigger: "blur" }
                ],
                type: [
                  { required: true, message: "单位类型 不能为空", trigger: "blur" }
                ],
                linkMan: [
                  { required: true, message: "联系人 不能为空", trigger: "blur" }
                ],
                linkTel: [
                  { required: true, message: "联系手机 不能为空", trigger: "blur" }
                ],
                address: [
                  { required: true, message: "公司地址 不能为空", trigger: "blur" }
                ],
              },
              options: [
                {
                  label: "公司编号",
                  prop: "number",
                  type: 'text',
                  disabled:true,
                  height:62,
                  span: 8
                },
                {
                  label: "单位名称",
                  prop: "name",
                  type: "text",
                  height:62,
                  span: 8,
                },
                {
                  label: "单位类型",
                  prop: "type",
                  type: 'select',
                  height:62,
                  span: 8,
                  options:[
                    {label:'设备承建商',value:'1'},
                    {label:'土建承建商',value:'2'},
                    {label:'水电承建商',value:'3'},
                  ]
                },
                {
                  label: "联系人",
                  prop: "linkMan",
                  type: 'text',
                  maxLength: 20 ,
                  height:62,
                  span: 8,
                },
                {
                  label: "联系手机",
                  prop: "linkTel",
                  type: 'text',
                  maxLength: 20 ,
                  height:62,
                  span: 8,
                },
                {
                  label: "邮箱",
                  prop: "email",
                  type: 'text',
                  maxLength: 20 ,
                  height:62,
                  span: 8,
                },
                {
                  label: "公司地址",
                  prop: "address",
                  type: 'text',
                  span: 24,
                  height:62,
                  maxLength: 100,
                },
              ]
            },
            formOptions2:{
              labelWidth: "160px",
              rules: {
                bankAccountName: [
                  { required: true, message: "账户名称 不能为空", trigger: "blur" }
                ],
                bankAccount: [
                  { required: true, message: "银行卡号 不能为空", trigger: "blur" }
                ],
                bankName: [
                  { required: true, message: "开户银行 不能为空", trigger: "blur" }
                ],
                bankCode: [
                  { required: true, message: "银行行号 不能为空", trigger: "blur" }
                ],
              },
              options: [
                {
                  label: "账户名称",
                  prop: "bankAccountName",
                  type: 'text',
                  maxLength: 120 ,
                  height:62,
                  span: 12
                },
                {
                  label: "银行卡号",
                  prop: "bankAccount",
                  type: 'text',
                  maxLength: 120 ,
                  height:62,
                  span: 12,
                },
                {
                  label: "开户银行",
                  prop: "bankName",
                  type: 'text',
                  maxLength: 120 ,
                  height:62,
                  span: 12,
                },
                {
                  label: "银行行号",
                  prop: "bankCode",
                  type: 'text',
                  maxLength: 120 ,
                  height:62,
                  span: 12,
                },
              ]
            },
            formOptions1Clone:{
              labelWidth: "160px",
              rules: {
                leCode : [
                  { required: true, message: "承建商主体编码 不能为空", trigger: "blur" }
                ],
                number: [
                  { required: true, message: "公司编号 不能为空", trigger: "blur" }
                ],
                name: [
                  { required: true, message: "单位名称 不能为空", trigger: "blur" }
                ],
                type: [
                  { required: true, message: "单位类型 不能为空", trigger: "blur" }
                ],
                linkMan: [
                  { required: true, message: "联系人 不能为空", trigger: "blur" }
                ],
                linkTel: [
                  { required: true, message: "联系手机 不能为空", trigger: "blur" }
                ],
                address: [
                  { required: true, message: "公司地址 不能为空", trigger: "blur" }
                ],
              },
              options: [
                {
                  label: "承建商主体编码",
                  prop: "leCode",
                  type: 'text',
                  maxLength: 30,
                  height:62,
                  span: 12,
                },
                {
                  label: "单位名称",
                  prop: "name",
                  type: "text",
                  height:62,
                  span: 12,
                },
                {
                  label: "公司编号",
                  prop: "number",
                  type: 'text',
                  disabled:true,
                  height:62,
                  span: 8
                },
                {
                  label: "单位类型",
                  prop: "type",
                  type: 'select',
                  height:62,
                  span: 8,
                  options:[
                    {label:'设备承建商',value:'1'},
                    {label:'土建承建商',value:'2'},
                    {label:'水电承建商',value:'3'},
                  ]
                },
                {
                  span: 8,
                  height:62,
                },
                {
                  label: "联系人",
                  prop: "linkMan",
                  type: 'text',
                  maxLength: 20 ,
                  height:62,
                  span: 8,
                },
                {
                  label: "联系手机",
                  prop: "linkTel",
                  type: 'text',
                  maxLength: 20 ,
                  height:62,
                  span: 8,
                },
                {
                  label: "邮箱",
                  prop: "email",
                  type: 'text',
                  maxLength: 20 ,
                  height:62,
                  span: 8,
                },
                {
                  label: "公司地址",
                  prop: "address",
                  type: 'text',
                  span: 24,
                  height:62,
                  maxLength: 100,
                },
              ]
            },
            formOptions2Clone:{
              labelWidth: "160px",
              rules: {
                bankAccountName: [
                  { required: true, message: "账户名称 不能为空", trigger: "blur" }
                ],
                bankAccount: [
                  { required: true, message: "银行卡号 不能为空", trigger: "blur" }
                ],
                bankName: [
                  { required: true, message: "开户银行 不能为空", trigger: "blur" }
                ],
                bankCode: [
                  { required: true, message: "银行行号 不能为空", trigger: "blur" }
                ],
              },
              options: [
                {
                  label: "账户名称",
                  prop: "bankAccountName",
                  type: 'text',
                  maxLength: 120 ,
                  height:62,
                  span: 12
                },
                {
                  label: "银行卡号",
                  prop: "bankAccount",
                  type: 'text',
                  maxLength: 120 ,
                  height:62,
                  span: 12,
                },
                {
                  label: "开户银行",
                  prop: "bankName",
                  type: 'text',
                  maxLength: 120 ,
                  height:62,
                  span: 12,
                },
                {
                  label: "银行行号",
                  prop: "bankCode",
                  type: 'text',
                  maxLength: 120 ,
                  height:62,
                  span: 12,
                },
              ]
            },
          }
      },
      watch:{
        'form.supplier':{
          handler(val){
            this.form.leCode = val.leCode
            this.form.name = val.name
          },
          deep:true
        }
      },
      created(){
        this.init()
        // 查询详情
        if (this.$route.query.id){
          this.loading = true
          getContractorMatchingDetail(this.$route.query.id).then(res=>{
            if (res.code==0){
              this.$set(this,'form',res.data)
              console.log(this.form)
            }
            this.loading = false
          }).catch(err=>{
            this.loading = false
          })
        }
      },
      methods:{
        init(){
          this.form.createName = this.$store.state.user.name+this.$store.state.user.account
          this.form.createTime = this.$zbPlugins.timeFormat(new Date(),'yyyy-MM-dd hh:mm:ss')
        },
        // 新增承建商
        addSupplier(){
          this.visible = true
          this.formClone = {supplier:{}}
          this.formClone.supplier.number = `JGCJS${this.$zbPlugins.timeFormat(null,'yyyyMMddhhmmss')}`
        },
        // 新增承建商 提交
        submitAddSupplier(){
          this.$refs["form2Clone"].validate(valid => {
            if (valid) {
              this.$refs["form2Clone"].validate(valid => {
                if (valid) {
                  this.loading = true
                  submitAddSupplier(this.formClone.supplier).then(res=>{
                    if (res.code==0){
                      this.$set(this,'form',Object.assign({},this.form,this.formClone))
                      this.$message.success('新增成功')
                      this.visible = false
                    }
                    this.loading = false
                  }).catch(()=>{
                    this.$message.error('新增失败')
                    this.loading = false
                  })
                }
              })
            }
          })
        },
        changeFlag(e){
          let checked = []
          let t = this.form.bpmInfos
          if (t && t.length){
            for (let i = 0; i < t.length; i++) {
              // 被选中的
              if (t[i].flag == 1){
                checked.push(t[i].instId)
              }
            }
          }
          getTotalBudget(checked).then(res=>{
            if (res.code==0){
              this.$set(this.form,'totalBudget',res.data)
            }
          })
        },
        getBpm(row){
          newWindowBpm(row.instId,1)
        },
        handleChange(val, key) {
        },
        canEditAdd(){
          return this.$route.query.type=='edit' || this.$route.query.type=='add'
        },
        showBpm(){
          this.showBpmDialog = true
          this.bpmUrl = 'www.baidu.com'
        },
        deleteLine(scope){
          this.sonList.splice(scope.$index,1)
        },
        addLine(){
          this.sonListItem.上传时间 = this.$zbPlugins.timeFormat()
          this.sonListItem.上传人 = this.$store.state.user.name
          this.sonList.push(this.$zbPlugins.deepClone(this.sonListItem))
          this.$refs.list.scrollTop = this.$refs.list.scrollHeight;
        },
        save(){
          this.form.status = ''
          this.loading = true
          if (this.form.id != undefined) {
            updateContractorMatchingDetail(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.loading = false;
            }).catch(()=>{this.loading = false});
          } else {
            addContractorMatchingDetail(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.loading = false;
            }).catch(()=>{this.loading = false});
          }
        },
        submit(){
          this.form.status = 'active'
          // 立项类型位 未批先建 或 数据补录 时，关联预算编制流程 可以为空
          if (this.form.projectBuildType!=3&&this.form.projectBuildType!=4){
            if (!this.form.bpmInfos
              || (this.form.bpmInfos && !this.form.bpmInfos.length )
              || (this.form.bpmInfos && this.form.bpmInfos.length && !this.form.bpmInfos.filter(i=>i.flag==1).length)){
              return this.$message.error('关联预算编制流程 不能为空')
            }
          }
          this.$refs["form1"].validate(valid => {
            if (valid){
              this.$refs["form2"].validate(valid => {
                if (valid){
                  this.$refs["form3"].validate(valid => {
                    if (valid){
                      this.loading = true
                      // 处理数据给后端
                      this.form.refInstIds = []
                      let t = this.form.bpmInfos
                      if (t && t.length){
                        for (let i = 0; i < t.length; i++) {
                          if (t[i].flag==1) this.form.refInstIds.push(t[i].instId)
                        }
                      }
                      let a = this.dealSendData({
                        createTime:'',
                        createName:'',
                      },this.form,true)
                      if (this.form.id != undefined) {
                        updateContractorMatchingDetail(a).then(response => {
                          this.msgSuccess("修改成功");
                          this.loading = false;
                          if (response.code==0){
                            newWindowBpm(response.data,null,{path:`/resourceMatching/contractorMatching`},true, Index)
                          }
                        }).catch(()=>{this.loading = false});
                      } else {
                        addContractorMatchingDetail(a).then(response => {
                          this.msgSuccess("新增成功");
                          this.loading = false;
                          if (response.code==0){
                            newWindowBpm(response.data,null,{path:`/resourceMatching/contractorMatching`},true, Index)
                          }
                        }).catch(()=>{this.loading = false});
                      }
                    }
                  })
                }
              })
            }
          });
        },
      }
    }
</script>
